/*
 *
 *  Copyright 2020 byai.com All right reserved. This software is the
 *  confidential and proprietary information of byai.com ("Confidential
 *  Information"). You shall not disclose such Confidential Information and shall
 *  use it only in accordance with the terms of the license agreement you entered
 *  into with byai.com.
 * /
 */

package com.straw.hat.springboot.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * @author jianshan@byai.com
 * @date 2020/4/15
 *
 */
@Configuration
public class ZookeeperConfig {

    private static final Logger LOG = LoggerFactory.getLogger(ZookeeperConfig.class);

    /**
     * zookeeper_Server地址列表 格式:Host1:Port1,Host2:Port2...
     */
    @Value("${zookeeper.address:127.0.0.1:2181}")
    private String zookeeperAddress;

    /**
     * 会话过期时间:单位毫秒,默认10s
     */
    @Value("${zookeeper.session.timeout:10000}")
    private int sessionTimeout;

    /**
     * 连接超时时间:单位毫秒,默认10s
     */
    @Value("${zookeeper.connection.timeout:10000}")
    private int connectionTimeout;


    /**
    * Zk_Client和Zk_Server断连之后,多久于Server连接一次基础值
    * */
    @Value("${zookeeper.base.retry.sleep.time:3000}")
    private int baseRetrySleepTime;

    /**
     *Zk_Client和Zk_Server断连之后,多久于Server连接一次最大值
     * */
    @Value("${zookeeper.max.retry.sleep.time:5000}")
    private int maxRetrySleepTime;

    /**
     * Zk_Client和Zk_Server断连之后,尝试多少次
     */
    @Value("${zookeeper.max.retry.times:3}")
    private int maxRetryTimes;


    public ZookeeperConfig() {
        LOG.info("ZookeeperConfig Construct");
    }

    @Bean(value = "curatorFramework")
    @Primary
    public CuratorFramework curatorFramework(){
        /*重试策略:增的停顿直到maxRetrySleepTime的重试*/
        LOG.info("Zookeeper_Configuration address:{},session_timeout:{},connection_timeout:{}",zookeeperAddress,sessionTimeout,connectionTimeout);
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(baseRetrySleepTime, maxRetryTimes,maxRetrySleepTime);
        return CuratorFrameworkFactory.builder()
                .connectString(zookeeperAddress)
                //Client和服务端通信过程中,多久超时
                .sessionTimeoutMs(sessionTimeout)
                //Client连接服务端多久超时
                .connectionTimeoutMs(connectionTimeout)
                //重试策略
                .retryPolicy(retryPolicy)
                .build();
    }
}
